package com.uaa.util;

import com.uaa.entity.ResultEnum;
import com.uaa.entity.ResultJson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @author iszengziqiang@163.com
 * @date 2021-08-25 15:04
 * @Version: 1.0
 * @desc
 */
@Slf4j
@RestControllerAdvice
public class GlobalException {

    /**
     * @param e
     * @return
     */
    @ExceptionHandler(HandleException.class)
    @ResponseBody
    public ResultJson handleException(HttpServletRequest request, HandleException e) {
        e.printStackTrace();
        log.info("####Error:systemMsg:{}####handleMsg:{}####requestUrl:{}", e.getMessage(), e.getErrorMsg(), request.getRequestURL().toString());
        showAllParams(request);
        return ResultJson.file(ResultEnum.getRe(e.getCode()));
    }

    /**
     * 用于打印错误请求的所有参数，方便排错
     *
     * @param request
     */
    private void showAllParams(HttpServletRequest request) {
        //需要打印异常的请求和参数(正式部署需要换一下)
        //if (ENV_PROD.contains(profile)) {
        if (true) {
            Enumeration paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = (String) paramNames.nextElement();
                String[] paramValues = request.getParameterValues(paramName);
                if (paramValues.length == 1) {
                    String paramValue = paramValues[0];
                    if (paramValue.length() != 0) {
                        log.info("####参数名:{}####参数值:{}", paramName, paramValue);
                    }
                }
            }
        }
    }

}
